<template>
<div class="app-container">
  <loading v-show="loading"></loading>
  <el-card class="box-card searchFormStyle" style="margin-bottom:1%;">
    <div slot="header" class="clearfix">
      <span>行政机构管理</span>
    </div>
    <div class="text item">
      <el-form ref="SearchDep" :model="SearchDep" label-width="130px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="机构编码">
              <el-input v-model="SearchDep.orgCode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="机构名称">
              <el-input v-model="SearchDep.orgName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="父级机构">
              <el-popover
                placement="bottom"
                width="400"
                height="300px"
                trigger="click">
                <el-tree
                  :data="orgData"
                  :props="defaultProps"
                  accordion
                  @node-click="handleNodeClick"
                  >
                </el-tree>
                <el-input v-model="parentOrgName"  slot="reference" readonly></el-input>
              </el-popover>
              <el-input type="hidden" v-model="SearchDep.parOrg" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item>
              <el-button 
              type="primary" 
              icon="el-icon-plus"
              v-if="permissionHandle('department:openDialog')"
              @click="openDialog">
              新 增
               </el-button>
              <el-button 
              type="primary" 
              icon="el-icon-search"
               v-if="permissionHandle('department:getList')"
               @click="getList">
               查 询
               </el-button>
               <el-button 
              type="primary" 
              icon="el-icon-refresh"
               v-if="permissionHandle('department:getList')"
               @click="resetSearch">
               重 置
               </el-button>
              <el-button 
              type="info" 
              icon="el-icon-delete"
              v-if="permissionHandle('department:handleDelete')"
              @click="deleteDepar">
              删 除
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </el-card>
  <el-card class="box-card" style="margin-bottom:1%;">
    <div slot="header" class="clearfix">
      <span>行政机构列表</span>
    </div>
    <el-table
      :data="tableData"
      ref="tableData"
      border
      style="width: 100%;margin-bottom:1%;"
      @selection-change="handleSelectionChange"
      >
      <el-table-column
        type="selection"
        width="40">
      </el-table-column>
      <el-table-column
        label="机构编码"
        width="180">
        <template slot-scope="scope">
            {{ scope.row.orgCode }}
        </template>
      </el-table-column>
      <el-table-column
        label="机构名称"
        width="180">
        <template slot-scope="scope">
            {{ scope.row.orgName }}
        </template>
      </el-table-column>
      <el-table-column
        label="父级机构"
        width="180"
      >
        <template slot-scope="scope">
            {{ scope.row.parOrg }}
        </template>
      </el-table-column>
      <el-table-column
        label="机构类别"
        width="180"
      >
        <template slot-scope="scope">
            {{ scope.row.orgType }}
        </template>
      </el-table-column>
      <el-table-column label="机构描述">
        <template slot-scope="scope">
          {{ scope.row.orgDesc }}
        </template>
      </el-table-column>
      <el-table-column label="排序编码">
        <template slot-scope="scope">
          {{ scope.row.orgNumber }}
        </template>
      </el-table-column>   
      <el-table-column
        label="创建日期"
        width="180"
        prop="createTime"
      >
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作"  width="200px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            icon="el-icon-edit-outline"
            v-if="permissionHandle('department:handleEdit')"
            @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button
            size="mini"
            icon="el-icon-delete"
            type="danger"
            v-if="permissionHandle('department:handleDelete')"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination @handleCurrentChange="handleCurrentChange" @handleSizeChange="handleSizeChange" :paginations="paginations"></pagination>
  </el-card>
  <!--新增角色-->
  <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="70%">
    <el-form :model="addForm" :rules="rules" ref="addForm" label-width="100px">
      <el-row>
          <el-col :span="12">
            <el-form-item label="机构编码" prop="orgCode">
              <el-input v-model="addForm.orgCode" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
           <el-form-item label="父级机构" class="tree-input">
             <el-popover
                placement="bottom"
                width="400"
                height="300px"
                trigger="click">
                <el-tree
                  :data="orgData"
                  show-checkbox
                  :props="defaultProps"
                  check-strictly
                  ref="orgTree"
                  node-key="orgKey"
                  :default-checked-keys="[addForm.parOrg]"
                  accordion
                  @check="handleClick"
                  >
                </el-tree>
                <el-input v-model="parentOrgName"  slot="reference" readonly></el-input>
              </el-popover>
              <el-input type="hidden" v-model="addForm.parOrg" auto-complete="off"></el-input>
           </el-form-item>
         </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
            <el-form-item label="机构名称" prop="orgName">
              <el-input v-model="addForm.orgName" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构类型" prop="orgType">
              <el-select v-model="addForm.orgType" placeholder="请选择机构类型" style="width:100%;">
                <el-option v-for="item in options" :label="item.paramName" :value="item.paramValue" :key="item.paramValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
            <el-form-item label="机构排序" prop="orgNumber">
              <el-input v-model="addForm.orgNumber" auto-complete="off"></el-input>
            </el-form-item>
        </el-col>
        <el-col :span="12">
           <el-form-item label="机构描述" prop="orgDesc">
              <el-input type="textarea" v-model="addForm.orgDesc" auto-complete="off"></el-input>
            </el-form-item>
         </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button icon="el-icon-refresh" @click="resetForm('addForm')">重置</el-button>
      <el-button icon="el-icon-plus" type="primary" @click="submitForm('addForm')">确 定</el-button>
    </div>
  </el-dialog>
</div>
</template>
<script>
import Loading from '@/components/loading/loading'
import pagination from '@/components/pagination/index'
import { getAllDepartment, getDepartmentList, addDepartment, deleteDepartment, changeDepartment } from '@/api/resource/department'
import { transform } from '@/utils/trans'
import { isvalidNumber, isvalidRequire, isvalidSpecial } from '@/utils/validate'
// 数字验证
var validNumber = (rule, value, callback) => {
  if (!isvalidNumber(value)) {
    callback(new Error('请输入数字'))
  } else {
    callback()
  }
}
// 特殊字符
var validSpecial = (rule, value, callback) => {
  if (!isvalidSpecial(value)) {
    callback(new Error('数据不能包含特殊字符'))
  } else {
    callback()
  }
}
// 非空
var validateRequire = (rule, value, callback) => {
  if (!isvalidRequire(value)) {
    callback(new Error('数据格式不'))
  } else {
    callback()
  }
}
export default {
  components: {
    Loading,
    pagination
  },
  data() {
    this.permissionHandle = this.$permissionHandle
    return {
      dialogTitle: '',
      loading: false,
      SearchDep: {
        orgCode: '',
        orgName: '',
        parOrg: '',
        pageSize: '10',
        pageNum: '1'
      },
      paginations: {
        totalNum: 0,
        currentPage: 1,
        pageSize: 10
      },
      deleteDep: {
        orgKey: ''
      },
      deleteDepArry: [],
      options: [],
      allDepartmentData: [],
      tableData: [],
      // 新增角色数据
      addForm: {
        orgCode: '',
        orgName: '',
        parOrg: '',
        orgType: '',
        orgNumber: '',
        orgDesc: ''
      },
      parentOrgName: '',
      dialogFormVisible: false, // 新增弹出框状态
      // 列表所选数据集合
      multipleSelection: [],
      rules: {
        orgCode: [
          { required: true, message: '请输入正确的机构编码' },
          { message: '请输入正确的机构编码', validator: validNumber },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符' }
        ],
        orgName: [
          { required: true, message: '请输入机构名称' },
          { message: '数据不能包含特殊字符', validator: validateRequire },
          { min: 1, max: 85, message: '长度在 1 到 85 个字符' }
        ],
        orgType: [
          { required: true, message: '请选择机构类型', trigger: 'change' }
        ],
        orgNumber: [
          { required: true, message: '请输入正确的机构排序' },
          { message: '请输入正确的机构排序', validator: validNumber },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符' }
        ],
        orgDesc: [
          { message: '数据不能包含特殊字符', validator: validSpecial }
        ]
      },
      // 组织机构
      orgData: [],
      defaultProps: {
        value: 'orgKey',
        parentId: 'parOrg',
        children: 'children',
        label: 'orgName'
      },
      treeShow: false,
      treeOtherShow: false
    }
  },
  watch: {
    dialogFormVisible: function() {
      if (this.dialogFormVisible === false) {
        this.resetForm('addForm')
      }
    }
  },
  created() {
    this.getAll()
    this.getList()
  },
  methods: {
    // 修改时选择父级机构
    handleClick(data, checked, node) {
      if (data.orgKey !== this.addForm.orgKey) {
        this.parentOrgName = data.orgName
        this.addForm.parOrg = data.orgKey
        if (checked) {
          this.$refs.orgTree.setCheckedNodes([])
          this.$refs.orgTree.setCheckedNodes([data])
        // 交叉点击节点
        } else {
          this.$refs.orgTree.setCheckedNodes([])
        // 点击已经选中的节点，置空
        }
      } else {
        this.$message({
          showClose: true,
          message: '不能选择自身作为父级机构',
          type: 'warning'
        })
        this.$refs.orgTree.setCheckedNodes([])
      }
    },
    // 新增打开弹出框
    openDialog() {
      this.dialogFormVisible = true
      this.dialogTitle = '机构新增'
      this.addForm = {
        orgKey: ''
      }
      this.changeDep('add')
    },
    handleEdit(index, row) {
      this.addForm = {
        orgKey: row.orgKey
      }
      this.changeDep('edit')
      this.dialogFormVisible = true
      this.dialogTitle = '机构修改'
    },
    // 修改
    changeDep(parmater) {
      this.loading = true
      return new Promise((resolve, reject) => {
        changeDepartment(this.addForm).then(response => {
          this.options = response.data.orgTypeList
          if (parmater === 'edit') {
            this.addForm = response.data.entity
            this.addForm.orgNumber = this.addForm.orgNumber.toString()
            if (this.$refs.orgTree.getNode(this.addForm.parOrg)) {
              // 默认选中组织机构
              this.parentOrgName = this.$refs.orgTree.getNode(this.addForm.parOrg).data.orgName
              this.addForm.parOrg = this.$refs.orgTree.getNode(this.addForm.parOrg).data.orgKey
            } else {
              this.parentOrgName = ''
              this.addForm.parOrg = '-1'
            }
          }
          this.loading = false
          this.orgData = transform(response.data.parOrgList, 'orgKey', 'parOrg', 'children')
          // this.orgData = transform(this.allDepartmentData, 'orgKey', 'parOrg', 'children')
          // console.log(this.orgData)
          resolve()
        }).catch(error => {
          this.loading = false
          reject(error)
        })
      })
    },
    // 获取全部部门机构数据
    getAll() {
      return new Promise((resolve, reject) => {
        getAllDepartment().then(response => {
          this.allDepartmentData = response.data
          // console.log(this.allDepartmentData)
          this.orgData = transform(this.allDepartmentData, 'orgKey', 'parOrg', 'children')
          // console.log(this.orgData)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    getList() {
      this.SearchDep.pageNum = 1
      this.getDeparList()
      this.paginations.currentPage = 1
    },
    blurSearch() {
      this.getList()
    },
    getDeparList() {
      this.loading = true
      return new Promise((resolve, reject) => {
        getDepartmentList(this.SearchDep).then(response => {
          // console.log(this.SearchDep)
          this.tableData = response.data.items
          this.paginations.totalNum = parseInt(response.data.itemsTotalCount)
          resolve()
          this.loading = false
        }).catch(error => {
          this.loading = false
          reject(error)
        })
      })
    },
    // 新增
    addDepar() {
      this.loading = true
      if (!this.addForm.parOrg) {
        this.addForm.parOrg = '-1'
      }
      this.addForm.orgNumber = parseInt(this.addForm.orgNumber)
      return new Promise((resolve, reject) => {
        addDepartment(this.addForm).then(response => {
          resolve()
          this.getAll()
          this.getList()
          this.dialogFormVisible = false
          this.loading = false
        }).catch(error => {
          this.loading = false
          reject(error)
        })
      })
    },
    // 删除
    deleteDepar() {
      if (this.deleteDepArry.length) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return new Promise((resolve, reject) => {
            deleteDepartment({ 'orgKey': JSON.stringify(this.deleteDepArry) }).then(response => {
              resolve()
              this.loading = false
              this.getAll()
              this.getList()
              this.deleteDepArry = []
            }).catch(error => {
              this.loading = false
              this.deleteDepArry = []
              reject(error)
            })
          })
        }).catch(() => {
          this.deleteDepArry = []
          this.$refs.tableData.clearSelection()
          return
        })
      } else {
        this.$message({
          showClose: true,
          message: '请至少选择一条要删除的数据',
          type: 'warning'
        })
      }
    },
    hideTree() {
      this.treeShow = false
      this.treeOtherShow = false
    },
    handleDelete(index, row) {
      this.$refs.tableData.clearSelection()
      this.deleteDepArry = []
      this.deleteDepArry.push(row.orgKey)
      this.deleteDepar()
    },
    handleSelectionChange(val) {
      this.deleteDepArry = []
      this.multipleSelection = val
      this.multipleSelection.forEach(element => {
        this.deleteDepArry.push(element.orgKey)
      })
    },
    // 改变分页的时候查询数据
    handleSizeChange(val) {
      this.SearchDep.pageSize = val
      this.getDeparList()
    },
    handleCurrentChange(val) {
      this.SearchDep.pageNum = val
      this.getDeparList()
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addDepar()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      if (this.addForm.orgKey) {
        this.changeDep('edit')
      } else {
        this.addForm = {
          orgCode: '',
          orgName: '',
          parOrg: '',
          orgType: '',
          orgNumber: '',
          orgDesc: ''
        }
        this.$refs.orgTree.setCheckedNodes([])
        this.parentOrgName = ''
        this.addForm.parOrg = ''
        this.$refs[formName].resetFields()
      }
    },
    handleNodeClick(data) {
      this.parentOrgName = data.orgName
      this.SearchDep.parOrg = data.orgKey
    },
    resetSearch() {
      this.SearchDep.orgCode = ''
      this.SearchDep.orgName = ''
      this.SearchDep.parOrg = ''
      this.getAll()
      this.getList()
    }
  }
}
</script>
<style lang="scss" scoped>
  .tree-input{
    position: relative;
  }
  .input-tree{
      height:200px;width: 100%;
      .el-scrollbar__wrap{overflow: auto;}
    }
    .tree-select{width: 100%;}
</style>
